# coding:utf8
__author__ = 'golker'


def config_context_processor(app):
    from golsee import models
    from models import Permission

    #: blog基本信息
    @app.context_processor
    def info():
        binfo = models.Blog_info.info()
        blog_name = models.Settings.query.filter(models.Settings.type == 'blog_name',
                                                 models.Settings.is_use == 1).first().value
        ten_comments = models.Comments.ten_newest()
        return dict(visit_all=binfo.visit_all,
                    visit_day=binfo.visit_day,
                    visit_month=binfo.visit_month,
                    visit_attack=binfo.visit_attack,
                    visit_attack_day=binfo.visit_attack_day,
                    visit_robot=binfo.visit_robot,
                    visit_robot_day=binfo.visit_robot_day,
                    article_all=binfo.article_all,
                    article_month=binfo.article_month,
                    user_all=binfo.user_all,
                    login_all=binfo.login_all,
                    blog_name=blog_name,
                    comment_all=binfo.comment_all,
                    comment_month=binfo.comment_month,
                    comment_day=binfo.comment_day,
                    ten_comments=ten_comments)

    #: 访问最多的10个文章
    @app.context_processor
    def top_ten():
        art = models.Article.top(10)
        return dict(top_ten=art)

    #: 每月文章统计
    @app.context_processor
    def month_count():
        count = models.Article.count_by_month()
        return dict(month_count=count)

    #: 一级菜单
    @app.context_processor
    def first_bar():
        bar = models.Settings.first_bar()
        return dict(first_bar=bar)

    #: 后台二级菜单
    @app.context_processor
    def admin_second_bar():
        bar = models.Settings.admin_second_bar()
        return dict(admin_second_bar=bar)

    #: 博主信息
    @app.context_processor
    def admin_user():
        admin_role = models.Role.query.filter_by(permissions=0xff).first()
        admin = models.User.query.filter_by(role=admin_role.id).first()
        return dict(admin_name=admin.nicename,
                    admin_img=admin.avatar(20),
                    admin_info=admin.info)

    #: 权限控制
    @app.context_processor
    def inject_permissions():
        return dict(Permission=Permission)

    #: 评论
    @app.context_processor
    def count_comment_times():
        def comment_times(id):
            times = models.Comments.query.filter_by(article_id=id).count()
            return times

        return dict(comment_times=comment_times)

    @app.context_processor
    def if_list():
        def is_list(l):
            if type(l) == list:
                return True
            else:
                return False

        return dict(is_list=is_list)
